<?php

namespace App\Repository;

use App\Common\Libs\PasswordHash;
use App\Consts\GlobalConst;
use App\Consts\GlobalDynamicConst;
use App\Consts\GlobalRelationshipConst;
use App\Models\Select\UserSelect;
use App\Models\User;
use App\Models\UserAttention;
use App\Models\UserFollowingRelationship;
use Illuminate\Database\Eloquent\Builder;

/**
 * @package App\Repository
 * @see UserRepository
 */
class UserRepository extends BaseRepository
{

    /**
     * search user list
     * @param $params
     * @return mixed|Builder
     */
    public function searchUserLit($params)
    {
        $model = new User();
        $provider = $model::getInstance()
            ->select($model->fields['search'])
            ->where(function (Builder $query) use ($params) {
                if (!empty($params['keywords_user'])) {
                    $query->where('nickname', 'like', "%" . $params['keywords_user'] . "%");
                }
                if (!empty($params['last_id'])) {
                    $query->where('user_id', '<', $params['last_id']);
                }
            })
            ->orderBy('user_id', 'desc')
            ->orderBy('created_at', 'desc');
        return $provider;
    }

    /**
     * 新增用户
     * @param $loadData
     * @return Builder|User
     */
    public function create($loadData)
    {
        $model = new User();

        return $model::getInstance()->create($loadData);
    }

    /**
     * 修改用户信息
     * @param User $user
     * @param $loadData
     * @return false|User
     */
    public function updateUser(User $user, $loadData)
    {
        return $user->updateFormat($loadData);
    }

    /**
     * 修改用户密码
     * @param User $user
     * @param $newPassword
     * @return false|int
     */
    public function changeUserPassword(User $user, $newPassword)
    {
        return $user->update([
            'password_hash' => PasswordHash::generatePasswordHash($newPassword)
        ]);
    }

    /**
     * get user by ids
     * @param $idAry
     * @return Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public function getUserByIdAry($idAry)
    {
        $model = new User();
        return $model::getInstance()
            ->select($model->fields['message'])
            ->whereIn('user_id', $idAry)
            ->get();
    }

    /**
     * 通过手机号获取用户
     * @param $phone
     * @param array $fields
     * @return Builder|\App\Models\User|object|null
     */
    public function getUserByPhone($phone, $fields = ['*'])
    {
        return User::getInstance()
            ->select($fields)
            ->where('phone', $phone)
            ->first();
    }

    /**
     * @param string $userId
     * @param array $selectScene
     * @return Builder|User|object|null
     */
    public function getUserByUserId($userId, $selectScene = UserSelect::BASE_INFO)
    {
        return User::getInstance()
            ->select(UserSelect::getSelects($selectScene))
            ->where('user_id', collect($userId)->unique()->values()->all())
            ->where('is_deleted', 0)
            ->first();
    }

    /**
     * [!] 注意这里是 id ，而不是 user_id
     * @param $id
     * @param string $selectScene
     * @return User|Builder|\Illuminate\Database\Eloquent\Model|mixed|object|null
     */
    public function getUserById($id, $selectScene = UserSelect::BASE_INFO)
    {
        return User::getInstance()
            ->select(UserSelect::getSelects($selectScene))
            ->where('id', collect($id)->unique()->values()->all())
            ->where('is_deleted', 0)
            ->first();
    }

    /**
     * 通过用户ID数组批量获取用户
     * @param string|array $userId
     * @param string $selectScene
     * @return Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public function getUserByUserIdArr($userId, $selectScene = UserSelect::BASE_INFO)
    {
        return User::getInstance()
            ->select(UserSelect::getSelects($selectScene))
            ->whereIn('user_id', (array)$userId)
            ->get();
    }

    /**
     * 通过主体用户ID和主体ID删除关注记录
     *
     * 该用户所有的粉丝的[user_attention_]记录均删除
     * @param $userAttentionId
     * @param $targetId
     * @return bool
     */
    public static function deleteByUserAttentionIdAndTargetId($userAttentionId, $targetId)
    {
        $relationships = UserFollowingRelationship::getModel($userAttentionId)
            ->where('user_id', $userAttentionId)
            ->whereIn('attention_status', [GlobalRelationshipConst::ATTENTION_STATUS_FANS, GlobalRelationshipConst::ATTENTION_STATUS_EACH])
            ->get();

        foreach ($relationships as $relationship) {
            UserAttention::getModel($relationship->follow_id)
                ->where('target_id', $targetId)
                ->update(['is_deleted' => GlobalConst::IS_DELETED, 'is_view' => GlobalDynamicConst::IS_NOT_VIEW]);
        }

        UserAttention::getModel($userAttentionId)
            ->where('target_id', $targetId)
            ->update(['is_deleted' => GlobalConst::IS_DELETED, 'is_view' => GlobalDynamicConst::IS_NOT_VIEW]);

        return true;
    }

}
